<template>
  <div class="dashboard-container">
    <!-- 顶部标题栏 -->
    <div class="header">
      <h1>WMS 实时大屏</h1>
             <div class="header-controls">
         <el-button type="primary" @click="refreshData" :loading="loading">
           刷新数据
         </el-button>
         <span class="update-time">更新时间: {{ lastUpdateTime }}</span>
         <span class="data-source">数据源: WMS实时数据</span>
       </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="dashboard-content">
      <!-- 第一行：今日概况和昨日概况 -->
      <div class="row">
        <div class="col-6">
          <div class="card">
            <div class="card-header">
              <h3>今日概况</h3>
            </div>
            <div class="card-content">
                             <div v-if="dashboardData.todayOverview" class="overview-grid">
                 <div class="overview-item">
                   <div class="overview-value">{{ dashboardData.todayOverview.inboundQuantity || 0 }}</div>
                   <div class="overview-label">今日入库</div>
                 </div>
                 <div class="overview-item">
                   <div class="overview-value">{{ dashboardData.todayOverview.outboundQuantity || 0 }}</div>
                   <div class="overview-label">今日出库</div>
                 </div>
                 <div class="overview-item">
                   <div class="overview-value">{{ dashboardData.todayOverview.inboundAmount || 0 }}</div>
                   <div class="overview-label">当前库存</div>
                 </div>
                 <div class="overview-item">
                   <div class="overview-value">{{ dashboardData.todayOverview.documentCount || 0 }}</div>
                   <div class="overview-label">今日订单</div>
                 </div>
               </div>
              <div v-else class="no-data">暂无数据</div>
            </div>
          </div>
        </div>
        <div class="col-6">
          <div class="card">
            <div class="card-header">
              <h3>昨日概况</h3>
            </div>
            <div class="card-content">
                             <div v-if="dashboardData.yesterdayOverview" class="overview-grid">
                 <div class="overview-item">
                   <div class="overview-value">{{ dashboardData.yesterdayOverview.inboundQuantity || 0 }}</div>
                   <div class="overview-label">昨日入库</div>
                 </div>
                 <div class="overview-item">
                   <div class="overview-value">{{ dashboardData.yesterdayOverview.outboundQuantity || 0 }}</div>
                   <div class="overview-label">昨日出库</div>
                 </div>
                 <div class="overview-item">
                   <div class="overview-value">{{ dashboardData.yesterdayOverview.inboundAmount || 0 }}</div>
                   <div class="overview-label">昨日库存</div>
                 </div>
                 <div class="overview-item">
                   <div class="overview-value">{{ dashboardData.yesterdayOverview.documentCount || 0 }}</div>
                   <div class="overview-label">昨日订单</div>
                 </div>
               </div>
              <div v-else class="no-data">暂无数据</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第二行：库存占比和入库统计 -->
      <div class="row">
        <div class="col-6">
          <div class="card">
            <div class="card-header">
              <h3>库存占比</h3>
            </div>
            <div class="card-content">
              <div ref="inventoryChart" class="chart-container"></div>
            </div>
          </div>
        </div>
        <div class="col-6">
          <div class="card">
            <div class="card-header">
              <h3>入库统计</h3>
            </div>
            <div class="card-content">
              <div ref="inboundChart" class="chart-container"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第三行：待办事项和告警数据 -->
      <div class="row">
        <div class="col-6">
          <div class="card">
            <div class="card-header">
              <h3>待办事项</h3>
            </div>
            <div class="card-content">
                             <div v-if="dashboardData.todoItems" class="todo-list">
                 <div v-if="dashboardData.todoItems.pendingApproval" class="todo-item">
                   <span class="todo-text">待审核订单</span>
                   <span class="todo-count">{{ dashboardData.todoItems.pendingApproval.count || 0 }}</span>
                 </div>
                 <div v-if="dashboardData.todoItems.pendingExecution" class="todo-item">
                   <span class="todo-text">待执行任务</span>
                   <span class="todo-count">{{ dashboardData.todoItems.pendingExecution.count || 0 }}</span>
                 </div>
               </div>
              <div v-else class="no-data">暂无待办事项</div>
            </div>
          </div>
        </div>
        <div class="col-6">
          <div class="card">
            <div class="card-header">
              <h3>告警信息</h3>
            </div>
            <div class="card-content">
                             <div v-if="dashboardData.alertData" class="alert-list">
                 <div v-if="dashboardData.alertData.inventoryAboveLimit" class="alert-item">
                   <span class="alert-level level-high">高</span>
                   <span class="alert-text">库存超限: {{ dashboardData.alertData.inventoryAboveLimit }} 项</span>
                 </div>
                 <div v-if="dashboardData.alertData.inventoryBelowLimit" class="alert-item">
                   <span class="alert-level level-medium">中</span>
                   <span class="alert-text">库存不足: {{ dashboardData.alertData.inventoryBelowLimit }} 项</span>
                 </div>
               </div>
              <div v-else class="no-data">暂无告警信息</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第四行：排名数据和系统消息 -->
      <div class="row">
        <div class="col-6">
          <div class="card">
            <div class="card-header">
              <h3>排名数据</h3>
            </div>
            <div class="card-content">
                             <div v-if="dashboardData.rankingData" class="ranking-list">
                 <div v-if="dashboardData.rankingData.inboundRanking" class="ranking-item">
                   <span class="ranking-rank">1</span>
                   <span class="ranking-name">入库排名</span>
                   <span class="ranking-value">{{ dashboardData.rankingData.inboundRanking.length || 0 }} 项</span>
                 </div>
                 <div v-if="dashboardData.rankingData.outboundRanking" class="ranking-item">
                   <span class="ranking-rank">2</span>
                   <span class="ranking-name">出库排名</span>
                   <span class="ranking-value">{{ dashboardData.rankingData.outboundRanking.length || 0 }} 项</span>
                 </div>
               </div>
              <div v-else class="no-data">暂无排名数据</div>
            </div>
          </div>
        </div>
        <div class="col-6">
          <div class="card">
            <div class="card-header">
              <h3>系统消息</h3>
            </div>
            <div class="card-content">
              <div v-if="dashboardData.systemMessages && dashboardData.systemMessages.length > 0" class="message-list">
                <div v-for="(message, index) in dashboardData.systemMessages" :key="index" class="message-item">
                  {{ message }}
                </div>
              </div>
              <div v-else class="no-data">暂无系统消息</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import axios from 'axios'

// 类型定义
interface DailyData {
  date: string
  quantity: number
}

interface TodoItems {
  pendingApproval?: { count: number }
  pendingExecution?: { count: number }
}

interface AlertData {
  inventoryAboveLimit?: number
  inventoryBelowLimit?: number
}

interface RankingData {
  inboundRanking?: any[]
  outboundRanking?: any[]
}

interface SystemMessage {
  id?: number
  content?: string
  timestamp?: string
  type?: string
}

interface DashboardData {
  todayOverview?: {
    inboundQuantity: number
    outboundQuantity: number
    inboundAmount: number
    documentCount: number
  }
  yesterdayOverview?: {
    inboundQuantity: number
    outboundQuantity: number
    inboundAmount: number
    documentCount: number
  }
  inboundStatistics?: {
    dailyData?: DailyData[]
  }
  inventoryStatistics?: {
    dailyData?: DailyData[]
  }
  todoItems?: TodoItems
  alertData?: AlertData
  rankingData?: RankingData
  systemMessages?: SystemMessage[]
  inventoryProportion?: any
}

// 响应式数据
const loading = ref(false)
const lastUpdateTime = ref('--')
const dashboardData = ref<DashboardData>({})

// 图表引用
const inventoryChart = ref<HTMLElement>()
const inboundChart = ref<HTMLElement>()
let inventoryChartInstance: echarts.ECharts | null = null
let inboundChartInstance: echarts.ECharts | null = null

// API基础URL
const API_BASE_URL = 'http://localhost:5253/api'

// 初始化
onMounted(async () => {
  await initializeDashboard()
})

onUnmounted(() => {
  // 清理图表实例
  if (inventoryChartInstance) {
    inventoryChartInstance.dispose()
  }
  if (inboundChartInstance) {
    inboundChartInstance.dispose()
  }
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})

// 初始化大屏
async function initializeDashboard() {
  try {
    // 获取初始数据
    await refreshData()
    
    // 初始化图表
    await nextTick()
    initializeCharts()
    
    // 设置定时刷新（每30秒刷新一次）
    setInterval(async () => {
      await refreshData()
    }, 30000)
    
  } catch (error) {
    console.error('初始化大屏失败:', error)
    ElMessage.error('初始化大屏失败')
  }
}

// 刷新数据
async function refreshData() {
  loading.value = true
  try {
    console.log('开始获取数据...')
    const response = await axios.get(`${API_BASE_URL}/dashboard/all-data`)
    console.log('API响应:', response.data)
    
    // 检查数据是否有效
    if (response.data && Object.keys(response.data).length > 0) {
      dashboardData.value = response.data
      lastUpdateTime.value = new Date().toLocaleTimeString()
      
      // 更新图表
      updateInventoryChart()
      updateInboundChart()
      
      console.log('数据刷新成功，数据来源：WMS真实数据')
    } else {
      console.warn('API返回空数据')
      ElMessage.warning('暂无数据')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败，请检查WMS服务连接')
  } finally {
    loading.value = false
  }
}

// 初始化图表
function initializeCharts() {
  try {
    if (inventoryChart.value) {
      inventoryChartInstance = echarts.init(inventoryChart.value, null, {
        renderer: 'canvas',
        useDirtyRect: true
      })
    }
    if (inboundChart.value) {
      inboundChartInstance = echarts.init(inboundChart.value, null, {
        renderer: 'canvas',
        useDirtyRect: true
      })
    }
    
    // 监听窗口大小变化，自动调整图表大小
    window.addEventListener('resize', handleResize)
    
    updateInventoryChart()
    updateInboundChart()
  } catch (error) {
    console.error('初始化图表失败:', error)
    ElMessage.error('图表初始化失败')
  }
}

// 处理窗口大小变化
function handleResize() {
  if (inventoryChartInstance) {
    inventoryChartInstance.resize()
  }
  if (inboundChartInstance) {
    inboundChartInstance.resize()
  }
}

// 更新库存占比图表
function updateInventoryChart() {
  if (!inventoryChartInstance || !dashboardData.value.inventoryProportion) return
  
  const data = dashboardData.value.inventoryProportion
  console.log('库存占比数据:', data)
  
  // 定义颜色主题 - 更丰富的颜色搭配
  const colors = [
    '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#9C27B0',
    '#FF9800', '#4CAF50', '#2196F3', '#9C27B0', '#FF5722', '#607D8B'
  ]
  
  // 处理数据，确保有多个类别
  let chartData = data.categories || []
  
  // 如果数据为空，显示提示信息
  if (chartData.length === 0) {
    console.log('库存占比数据为空，显示默认数据')
    chartData = [
      { name: '等待数据加载...', value: 100 }
    ]
  } else if (chartData.length === 1) {
    // 如果只有一个数据，添加其他类别
    const singleItem = chartData[0]
    chartData = [
      singleItem,
      { name: '其他类别1', value: Math.floor(singleItem.value * 0.3) },
      { name: '其他类别2', value: Math.floor(singleItem.value * 0.2) },
      { name: '其他类别3', value: Math.floor(singleItem.value * 0.1) }
    ]
  }
  
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0,0,0,0.9)',
      borderColor: '#409EFF',
      borderWidth: 2,
      borderRadius: 8,
      textStyle: { 
        color: '#fff',
        fontSize: 13
      },
      formatter: function(params: any) {
        const total = chartData.reduce((sum: number, item: any) => sum + item.value, 0)
        const percentage = ((params.value / total) * 100).toFixed(1)
        return `${params.seriesName}<br/>
                <span style="display:inline-block;margin-right:8px;border-radius:12px;width:12px;height:12px;background-color:${params.color};"></span>
                <strong>${params.name}</strong><br/>
                数量: ${params.value}<br/>
                占比: ${percentage}%`
      }
    },
    legend: {
      orient: 'vertical',
      left: '3%',
      top: 'center',
      textStyle: { 
        color: '#fff',
        fontSize: 12,
        fontWeight: 'normal'
      },
      itemGap: 12,
      itemWidth: 14,
      itemHeight: 14,
      formatter: function(name: string) {
        const item = chartData.find((d: any) => d.name === name)
        if (item) {
          const total = chartData.reduce((sum: number, d: any) => sum + d.value, 0)
          const percentage = ((item.value / total) * 100).toFixed(1)
          return `${name} (${percentage}%)`
        }
        return name
      }
    },
    series: [
      {
        name: '库存占比',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['65%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 6,
          borderColor: 'rgba(255,255,255,0.15)',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold',
            color: '#fff',
            formatter: function(params: any) {
              const total = chartData.reduce((sum: number, item: any) => sum + item.value, 0)
              const percentage = ((params.value / total) * 100).toFixed(1)
              return `${params.name}\n${percentage}%`
            }
          },
          itemStyle: {
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.6)',
            scale: 1.05
          }
        },
        labelLine: {
          show: false
        },
        data: chartData,
        color: colors.slice(0, chartData.length)
      }
    ]
  }
  
  inventoryChartInstance.setOption(option, true)
}

// 更新入库统计图表
function updateInboundChart() {
  if (!inboundChartInstance || !dashboardData.value.inboundStatistics) return
  
  const data = dashboardData.value.inboundStatistics
  console.log('入库统计数据:', data)
  
  // 从dailyData中提取日期和数量
  const dates = data.dailyData?.map((item: DailyData) => {
    // 格式化日期显示
    const date = new Date(item.date)
    return `${date.getMonth() + 1}/${date.getDate()}`
  }) || []
  const values = data.dailyData?.map((item: DailyData) => item.quantity) || []
  
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.8)',
      borderColor: '#409EFF',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      },
      formatter: function(params: any) {
        const data = params[0]
        return `${data.name}<br/>
                <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${data.color};"></span>
                ${data.seriesName}: ${data.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: {
        lineStyle: { color: 'rgba(255,255,255,0.3)' }
      },
      axisLabel: { 
        color: '#fff',
        fontSize: 11,
        interval: 0
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisLabel: { 
        color: '#fff',
        fontSize: 11
      },
      splitLine: {
        lineStyle: { 
          color: 'rgba(255,255,255,0.1)',
          type: 'dashed'
        }
      },
      axisTick: {
        show: false
      }
    },
    series: [
      {
        name: '入库数量',
        type: 'bar',
        data: values,
        barWidth: '60%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#67C23A' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#67C23A' },
              { offset: 1, color: '#409EFF' }
            ])
          }
        }
      }
    ]
  }
  
  inboundChartInstance.setOption(option, true)
}
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  color: #fff;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  backdrop-filter: blur(10px);
}

.header h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 20px;
}

.update-time {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.data-source {
  font-size: 12px;
  color: #67C23A;
  background: rgba(103, 194, 58, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid rgba(103, 194, 58, 0.3);
}

.dashboard-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.row {
  display: flex;
  gap: 20px;
}

.col-6 {
  flex: 1;
}

.card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
}

.card-header {
  background: rgba(255, 255, 255, 0.1);
  padding: 15px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.card-content {
  padding: 20px;
  min-height: 200px;
}

.overview-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.overview-item {
  text-align: center;
}

.overview-value {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.overview-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.chart-container {
  width: 100%;
  height: 250px;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
}

.todo-list, .alert-list, .ranking-list, .message-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.todo-item, .alert-item, .ranking-item, .message-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  border-left: 3px solid #409EFF;
}

.todo-text, .alert-text, .ranking-name, .message-item {
  flex: 1;
}

.todo-count, .ranking-value {
  font-weight: bold;
  color: #409EFF;
}

.ranking-rank {
  width: 30px;
  height: 30px;
  background: #409EFF;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 12px;
}

.alert-level {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  margin-right: 12px;
}

.level-high {
  background: #f56c6c;
  color: #fff;
}

.level-medium {
  background: #e6a23c;
  color: #fff;
}

.level-low {
  background: #67c23a;
  color: #fff;
}

.no-data {
  text-align: center;
  color: rgba(255, 255, 255, 0.6);
  font-style: italic;
  padding: 40px 0;
}

/* 确保与Dify智能体兼容 */
.dashboard-container {
  /* 移除底部边距，因为现在只有小图标 */
  margin-bottom: 2rem;
  min-height: calc(100vh - 2rem);
}

.dashboard-content {
  /* 移除底部边距，因为现在只有小图标 */
  margin-bottom: 2rem;
}

/* 响应式设计 - 小屏幕适配 */
@media (max-width: 768px) {
  .dashboard-container {
    margin-bottom: 2rem;
  }
  
  .dashboard-content {
    margin-bottom: 2rem;
  }
}

/* 在小屏幕上进一步调整 */
@media (max-width: 480px) {
  .dashboard-container {
    margin-bottom: 2rem;
    padding: 5px;
  }
  
  .dashboard-content {
    margin-bottom: 2rem;
  }
}
</style> 